function dpsave (filename,matname,X)
% SYNTAX: 
%	dpsave (filename,matname,X)
%
% Saves the nonzeroes of X in the file specified by filename.
% The object will be saved using the string matname.
%
% The file format, which is a valid Matlab script, can be parsed
% and loaded into any Diffpack matrix object. Please note that
% in contrast to Matlabs internal storage format, the generated
% script addresses the matrix entries row by row.
%
% Binary storage is not yet supported.

% $Id: dpsave.m,v 1.2 1994/10/12 08:31:02 bru Exp $

[nrows,ncolumns] = size(X);

is_vec = 0;

if ((nrows == 1) & (ncolumns > 1))
  is_vec = 1;
elseif ((nrows > 1) & (ncolumns == 1))
  is_vec = 1;
end

if ( max(max(abs(imag(X)))) == 0)
  complex_data = 0;
else
  complex_data = 1;
end


fid = fopen(filename,'w');


if (complex_data)
  fprintf(fid,'datatype = ''Complex'';\n\n');
else
  fprintf(fid,'datatype = ''real'';\n\n');
end


if (is_vec)

  fprintf(fid,'length = %d;\n ',length(X));
  fprintf(fid,[matname ' = zeros(length,1);\n\n']);

  fprintf(fid,['%% Data: \n\n']);

  if (complex_data)
    for i = 1:length(X)
      fprintf(fid,'%s(%d) = (%e,%e);\n',matname,i,real(X(i)),imag(X(i)));
    end
  else
    for i = 1:length(X)
      fprintf(fid,'%s(%d) = %e;\n',matname,i,X(i));
    end
  end

else
 
  [J,I,V] = find(X');  % extract nonzeroes (forces row-by-row sequence)
  nentries = length(V);

  fprintf(fid,'nrows = %d; ',nrows);
  fprintf(fid,'ncolumns = %d; \n',ncolumns);
  fprintf(fid,'nentries = %d;\n\n',nentries);
  fprintf(fid,[matname ' = spalloc(nrows,ncolumns,nentries);\n\n']);

  fprintf(fid,['%% Data: \n\n']);

  if (complex_data)
    for i = 1:nentries
      fprintf(fid,'%s(%d,%d) = (%e,%e);\n',matname,I(i),J(i),real(V(i)),imag(V(i)));
    end 
  else
    for i = 1:nentries
      fprintf(fid,'%s(%d,%d) = %e;\n',matname,I(i),J(i),V(i));
    end
  end

end

fclose(fid);

